package _18_剑指OfferII;

import java.util.Arrays;

public class _011_剑指OfferII0和1个数相同的子数组 {

    public int findMaxLength(int[] nums) {
        int len = nums.length;
        int[] map = new int[len << 1 + 1];
        Arrays.fill(map, -2);
        int maxLen = 0, total = 0;
        map[total + len] = -1;

        for (int i = 0; i < nums.length; i++) {
            total += nums[i] == 0? 1: -1;
            int index = map[total + len];
            if (index != -2) {
                int temp = i - index;
                if (temp > maxLen) {
                    maxLen = temp;
                }
            } else {
                map[total + len] = i;
            }
        }
        return maxLen;
    }

}
